<template>
    <div v-loading="props.baTable.form.loading">
        <el-form
            ref="formRef"
            :model="props.baTable.form.items"
            label-width="120px"
            :rules="rules"
            class="ba-form"
            label-position="right"
        >
            <!-- 基本信息 -->
            <el-card shadow="never" class="ba-form-card">
                <el-row :gutter="20">
                    <el-col :md="12" :xs="24">
                        <el-form-item :label="t('商品编号')" prop="code">
                            <el-input v-model="props.baTable.form.items.code" :placeholder="t('请输入商品编号')" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :md="12" :xs="24">
                        <el-form-item :label="t('商品名称')" prop="name">
                            <el-input v-model="props.baTable.form.items.name" :placeholder="t('请输入商品名称')" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :md="12" :xs="24" v-if="isSpecialType">
                        <el-form-item :label="t('商品条码')" prop="barcode">
                            <el-input v-model="props.baTable.form.items.barcode" :placeholder="t('请输入商品条码')" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :md="12" :xs="24">
                        <el-form-item :label="t('规格型号')" prop="spec">
                            <el-input v-model="props.baTable.form.items.spec" :placeholder="t('请输入规格型号')" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :md="12" :xs="24">
                        <FormItem :label="t('商品分类')" 
                    type="remoteSelect" v-model="props.baTable.form.items!.category" 
                    prop="category" 
                    :input-attr="{ 
                        pk: 'id', 
                        field: 'name', 
                        remoteUrl: '/admin/yxerp.Category/index',
                        params:{
                            search: [{
                                field: 'type',
                                val: 'product',
                                operator: 'eq',
                            }],
                         }
                        }" :placeholder="t('Please select field', { field: t('商品分类') })" />
                    </el-col>
                    <el-col :md="12" :xs="24">
                        <el-form-item :label="t('首选仓库')" prop="default_warehouse_id">
                            <el-select v-model="props.baTable.form.items.default_warehouse_id" class="w100" :placeholder="t('请选择首选仓库')">
                                <el-option v-for="item in state.warehouses" :key="item.id" :label="item.name" :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :md="12" :xs="24">
                        <el-form-item :label="t('状态')" prop="status">
                            <el-radio-group v-model="props.baTable.form.items.status">
                                <el-radio :label="1">{{ t('上架') }}</el-radio>
                                <el-radio :label="0">{{ t('下架') }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :md="12" :xs="24" v-if="isSpecialType">
                        <el-form-item :label="t('促销状态')" prop="promotion_status">
                            <el-radio-group v-model="props.baTable.form.items.promotion_status">
                                <el-radio :label="1">{{ t('是') }}</el-radio>
                                <el-radio :label="0">{{ t('否') }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :md="12" :xs="24" v-if="isSpecialType">
                        <el-form-item :label="t('订货通状态')" prop="order_status">
                            <el-radio-group v-model="props.baTable.form.items.order_status">
                                <el-radio :label="1">{{ t('上架') }}</el-radio>
                                <el-radio :label="0">{{ t('下架') }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :md="12" :xs="24">
                        <el-form-item :label="t('常用')" prop="is_popular">
                            <el-radio-group v-model="props.baTable.form.items.is_popular">
                                <el-radio :label="1">{{ t('是') }}</el-radio>
                                <el-radio :label="0">{{ t('否') }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :md="12" :xs="24">
                        <FormItem :label="t('商品类型')" 
                    type="remoteSelect" v-model="props.baTable.form.items!.category_id" 
                    prop="category_id" 
                    :input-attr="{ 
                        pk: 'id', 
                        field: 'name', 
                        remoteUrl: '/admin/yxerp.Category/index',
                        params:{
                            search: [{
                                field: 'type',
                                val: 'producttype',
                                operator: 'eq',
                            }],
                         }
                        }" :placeholder="t('Please select field', { field: t('商品类型') })" />
                    </el-col>
                     <el-col :md="12" :xs="24" v-if="isSpecialType">
                        <el-form-item :label="t('零售')" prop="is_retail">
                            <el-radio-group v-model="props.baTable.form.items.is_retail">
                                <el-radio :label="1">{{ t('是') }}</el-radio>
                                <el-radio :label="0">{{ t('否') }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-card>

            <!-- 计量单位设置 -->
            <el-card shadow="never" class="ba-form-card">
                <template #header>
                    <div class="card-header">
                        <span>{{ t('计量单位设置') }}</span>
                    </div>
                </template>
                <el-row :gutter="20">
                    <el-col :xs="24">
                        <el-form-item :label="t('计量单位')" prop="unit_id">
                            <el-select v-model="props.baTable.form.items.unit_id" class="w100" :placeholder="t('请选择计量单位')" @change="handleUnitChange">
                                <el-option v-for="item in state.units" :key="item.id" :label="item.name" :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :xs="24">
                        <el-form-item>
                            <el-checkbox 
                                v-model="state.useMultiUnit" 
                                @change="handleMultiUnitChange"
                            >{{ t('多计量单位') }}</el-checkbox>
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <!-- 多计量单位设置 -->
                <div v-if="state.useMultiUnit" class="multi-unit-table">
                    <el-table :data="state.unitTable" border style="width: 100%">
                        <el-table-column prop="name" label="计量单位" width="180">
                            <template #default="{row}">
                                {{ row.name }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="retail_price" label="零售价" width="180">
                            <template #default="{row}">
                                <el-input-number v-model="row.retail_price" :min="0" :precision="2" :step="0.01" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="wholesale_price" label="批发价" width="180">
                            <template #default="{row}">
                                <el-input-number v-model="row.wholesale_price" :min="0" :precision="2" :step="0.01" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="vip_price" label="vip会员价" width="180">
                            <template #default="{row}">
                                <el-input-number v-model="row.vip_price" :min="0" :precision="2" :step="0.01" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="discount1" label="折扣率1" width="180">
                            <template #default="{row}">
                                <el-input-number v-model="row.discount1" :min="0" :max="1" :precision="2" :step="0.01" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="discount2" label="折扣率2" width="180">
                            <template #default="{row}">
                                <el-input-number v-model="row.discount2" :min="0" :max="1" :precision="2" :step="0.01" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="purchase_price" label="预计采购价" width="180">
                            <template #default="{row}">
                                <el-input-number v-model="row.purchase_price" :min="0" :precision="2" :step="0.01" />
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-card>

            <!-- 价格策略设置 -->
            <el-card shadow="never" class="ba-form-card" v-if="!state.useMultiUnit && isSpecialType">
                <template #header>
                    <div class="card-header">
                        <span>{{ t('价格策略') }}</span>
                    </div>
                </template>
                <el-row :gutter="20">
                    <el-col :md="12" :xs="24">
                        <el-form-item :label="t('零售价')" prop="retail_price">
                            <el-input-number v-model="props.baTable.form.items.retail_price" :min="0" :precision="2" :step="0.01" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :md="12" :xs="24">
                        <el-form-item :label="t('批发价')" prop="wholesale_price">
                            <el-input-number v-model="props.baTable.form.items.wholesale_price" :min="0" :precision="2" :step="0.01" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :md="12" :xs="24">
                        <el-form-item :label="t('VIP会员价')" prop="vip_price">
                            <el-input-number v-model="props.baTable.form.items.vip_price" :min="0" :precision="2" :step="0.01" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :md="12" :xs="24">
                        <el-form-item :label="t('折扣率1')" prop="discount1">
                            <el-input-number v-model="props.baTable.form.items.discount1" :min="0" :max="1" :precision="2" :step="0.01" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :md="12" :xs="24">
                        <el-form-item :label="t('折扣率2')" prop="discount2">
                            <el-input-number v-model="props.baTable.form.items.discount2" :min="0" :max="1" :precision="2" :step="0.01" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :md="12" :xs="24">
                        <el-form-item :label="t('预计采购价')" prop="purchase_price">
                            <el-input-number v-model="props.baTable.form.items.purchase_price" :min="0" :precision="2" :step="0.01" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-card>

            <!-- 商品图片 -->
            <el-card shadow="never" class="ba-form-card">
                <template #header>
                    <div class="card-header">
                        <span>{{ t('商品主图') }}</span>
                    </div>
                </template>
                <el-row>
                    <el-col :xs="24">
                        <FormItem :label="t('商品主图')" type="image" v-model="props.baTable.form.items.image" />
                    </el-col>
                </el-row>
            </el-card>

            <el-card shadow="never" class="ba-form-card">
                <template #header>
                    <div class="card-header">
                        <span>{{ t('商品图集') }}</span>
                    </div>
                </template>
                <el-row>
                    <el-col :xs="24">
                        <FormItem :label="t('商品图集')" type="images" v-model="props.baTable.form.items.images" />

                    </el-col>
                </el-row>
            </el-card>

            <!-- SKU信息 -->
            <el-card shadow="never" class="ba-form-card" v-if="props.baTable.form.operate === 'Edit'">
                <template #header>
                    <div class="card-header">
                        <span>{{ t('SKU Information') }}</span>
                        <el-button type="primary" @click="openSkuForm('Add')">{{ t('Add SKU') }}</el-button>
                    </div>
                </template>
                <el-table :data="skuList" style="width: 100%">
                    <el-table-column prop="sku_code" :label="t('SKU Code')" width="180" />
                    <el-table-column prop="attributes" :label="t('Attributes')">
                        <template #default="scope">
                            <el-tag v-for="(attr, key) in scope.row.attributes" :key="key" class="mx-1">
                                {{ key }}: {{ attr }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="price" :label="t('Price')" width="120" />
                    <el-table-column prop="stock" :label="t('Stock')" width="120" />
                    <el-table-column :label="t('Operation')" width="200">
                        <template #default="scope">
                            <el-button type="primary" size="small" @click="openSkuForm('Edit', scope.row)">{{ t('Edit') }}</el-button>
                            <el-button type="danger" size="small" @click="delSku(scope.row)">{{ t('Delete') }}</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>

            <!-- 库存预警设置 -->
            <el-card shadow="never" class="ba-form-card">
                <template #header>
                    <div class="card-header">
                        <span>{{ t('库存预警') }}</span>
                    </div>
                </template>
                <el-row>
                    <el-col :xs="24">
                        <el-form-item>
                            <el-checkbox v-model="state.enableStockWarning">{{ t('库存预警') }}</el-checkbox>
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <!-- 分仓库预警 -->
                <div v-if="state.enableStockWarning">
                    <el-row>
                        <el-col :xs="24" class="ml-30">
                            <el-form-item>
                                <el-checkbox v-model="state.enableWarehouseWarning">{{ t('分仓预警') }}</el-checkbox>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <!-- 分仓预警设置 -->
                    <div v-if="state.enableWarehouseWarning">
                        <el-table :data="state.warehouseWarningList" border style="width: 100%; margin-left: 120px;">
                            <el-table-column prop="warehouse_name" label="仓库" width="200">
                                <template #default="{row}">
                                    {{ row.warehouse_name }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="min_stock" label="最低库存" width="200">
                                <template #default="{row}">
                                    <el-input-number v-model="row.min_stock" :min="0" :precision="0" :step="1" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="max_stock" label="最高库存" width="200">
                                <template #default="{row}">
                                    <el-input-number v-model="row.max_stock" :min="0" :precision="0" :step="1" />
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    
                    <!-- 统一设置 -->
                    <div v-else>
                        <el-row :gutter="20">
                            <el-col :md="12" :xs="24">
                                <el-form-item :label="t('最低库存')" prop="min_stock">
                                    <el-input-number v-model="props.baTable.form.items.min_stock" :min="0" :precision="0" :step="1" style="width: 100%" />
                                </el-form-item>
                            </el-col>
                            <el-col :md="12" :xs="24">
                                <el-form-item :label="t('最高库存')" prop="max_stock">
                                    <el-input-number v-model="props.baTable.form.items.max_stock" :min="0" :precision="0" :step="1" style="width: 100%" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </div>
            </el-card>

            <!-- 批次管理 -->
            <el-card shadow="never" class="ba-form-card">
                <template #header>
                    <div class="card-header">
                        <span>{{ t('批次管理') }}</span>
                    </div>
                </template>
                <el-row>
                    <el-col :xs="24">
                        <el-form-item>
                            <el-checkbox v-model="props.baTable.form.items.enable_batch_management">{{ t('启用批次保质期管理') }}</el-checkbox>
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <div v-if="props.baTable.form.items.enable_batch_management">
                    <el-row :gutter="20">
                        <el-col :md="12" :xs="24">
                            <el-form-item :label="t('保质期天数')" prop="shelf_life_days">
                                <el-input-number v-model="props.baTable.form.items.shelf_life_days" :min="0" :precision="0" :step="1" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                        <el-col :md="12" :xs="24">
                            <el-form-item :label="t('预警天数')" prop="warning_days">
                                <el-input-number v-model="props.baTable.form.items.warning_days" :min="0" :precision="0" :step="1" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
            </el-card>

            <!-- 序列号管理 -->
            <el-card shadow="never" class="ba-form-card">
                <template #header>
                    <div class="card-header">
                        <span>{{ t('序列号管理') }}</span>
                    </div>
                </template>
                <el-row>
                    <el-col :xs="24">
                        <el-form-item>
                            <el-checkbox v-model="props.baTable.form.items.enable_serial_management">{{ t('启用序列号') }}</el-checkbox>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-card>

            <!-- 期初设置 -->
            <el-card shadow="never" class="ba-form-card">
                <template #header>
                    <div class="card-header">
                        <span>{{ t('期初设置') }}</span>
                    </div>
                </template>
                <el-row>
                    <el-col :xs="24">
                        <el-form-item>
                            <el-checkbox v-model="props.baTable.form.items.enable_initial_setting">{{ t('期初设置') }}</el-checkbox>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-card>

            <!-- 商品详情 -->
            <el-card shadow="never" class="ba-form-card">
                <template #header>
                    <div class="card-header">
                        <span>{{ t('商品详情') }}</span>
                    </div>
                </template>
                <el-row>
                    <el-col :xs="24">
                       
                                <!-- 使用富文本编辑器 -->

                        <FormItem label="编辑器" type="editor" v-model="props.baTable.form.items.description" />
                    </el-col>
                </el-row>
            </el-card>
        </el-form>

        <!-- SKU弹窗表单 -->
        <el-dialog
            v-model="skuDialogVisible"
            :title="skuFormTitle"
            width="60%"
            :destroy-on-close="true"
            :close-on-click-modal="false"
        >
            <el-form ref="skuFormRef" :model="skuForm" label-width="120px">
                <el-form-item :label="t('SKU Code')" prop="sku_code">
                    <el-input v-model="skuForm.sku_code" :placeholder="t('Please input SKU code')" />
                </el-form-item>
                <el-form-item :label="t('Attributes')" prop="attributes">
                    <div v-for="(item, index) in attributesList" :key="index" class="attribute-item">
                        <el-input v-model="item.key" placeholder="属性名" style="width: 40%; margin-right: 10px;" />
                        <el-input v-model="item.value" placeholder="属性值" style="width: 40%;" />
                        <el-button @click="removeAttribute(index)" type="danger" circle icon="Delete" style="margin-left: 10px;" />
                    </div>
                    <el-button type="primary" @click="addAttribute" style="margin-top: 10px;">{{ t('Add Attribute') }}</el-button>
                </el-form-item>
                <el-form-item :label="t('Price')" prop="price">
                    <el-input-number v-model="skuForm.price" :min="0" :precision="2" :step="0.01" />
                </el-form-item>
                <el-form-item :label="t('Cost')" prop="cost">
                    <el-input-number v-model="skuForm.cost" :min="0" :precision="2" :step="0.01" />
                </el-form-item>
                <el-form-item :label="t('Stock')" prop="stock">
                    <el-input-number v-model="skuForm.stock" :min="0" :precision="0" :step="1" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="skuDialogVisible = false">{{ t('Cancel') }}</el-button>
                    <el-button type="primary" @click="submitSkuForm">{{ t('Confirm') }}</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed, watch, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { buildValidatorData } from '/@/utils/validate'
import { baTableApi } from '/@/api/common'
import { getNextCode,getcode } from '/@/api/backend/yxerp/coderule'
import { useUserInfo } from '/@/stores/userInfo'
import FormItem from '/@/components/formItem/index.vue'
import { cloneDeep, findIndex, merge } from 'lodash'
import { getSelectData } from '/@/api/common'
const { t } = useI18n()
const formRef = ref<FormInstance>()
const editorRef = ref<HTMLElement>()
const userInfo = useUserInfo()
const props = defineProps({
    baTable: {
        type: Object,
        required: true
    }
})
// 判断是否是特殊类型(category_id === 33)成品
const isSpecialType = ref(true)
// 监听商品类型变化
watch(() => props.baTable.form.items.category_id, (newVal) => {
    // 如果不是特殊类型，则设置相关字段的默认值
    if (newVal !== "33") {
        props.baTable.form.items.promotion_status = 0
        props.baTable.form.items.order_status = 0
        props.baTable.form.items.is_retail = 0
        props.baTable.form.items.barcode = ''
        props.baTable.form.items.retail_price = 0
        props.baTable.form.items.wholesale_price = 0
        props.baTable.form.items.vip_price = 0
        props.baTable.form.items.discount1 = 0
        props.baTable.form.items.discount2 = 0
        props.baTable.form.items.purchase_price = 0
        isSpecialType.value = false
    } else {
        isSpecialType.value = true
    }
}, { immediate: true }) // 添加immediate: true确保初始化时会执行一次

const api = new baTableApi('/admin/yxerp.sku/')
const skuList = ref<any[]>([])
const skuDialogVisible = ref(false)
const skuFormRef = ref<FormInstance>()
const skuForm = ref<any>({
    product_id: '',
    sku_code: '',
    price: 0,
    cost: 0,
    stock: 0,
    attributes: {}
})
const skuFormTitle = ref('')
const skuAction = ref('Add')
const attributesList = ref<{key: string, value: string}[]>([])

// 图片列表状态
const imagesList = ref<any[]>([])

// 表单验证规则
const rules = reactive<FormRules>({
    name: [{ required: true, message: t('请输入商品名称'), trigger: 'blur' }],
    code: [{ required: true, message: t('请输入商品编号'), trigger: 'blur' }],
    category_id: [{ required: true, message: t('请选择商品分类'), trigger: 'change' }],
    unit_id: [{ required: true, message: t('请选择计量单位'), trigger: 'change' }]
})

// 计量单位表格数据
interface UnitTableItem {
    name: string
    unit_code: string
    rate: number
    retail_price: number
    wholesale_price: number
    vip_price: number
    discount1: number
    discount2: number
    purchase_price: number
}

// 仓库预警数据
interface WarehouseWarningItem {
    warehouse_id: number | string
    warehouse_name: string
    min_stock: number
    max_stock: number
}

// 状态数据
const state = reactive({
    category: [] as Array<{id: number | string, name: string}>,
    warehouses: [] as Array<{id: number | string, name: string}>,
    units: [] as Array<{id: number | string, name: string, conversion: string, is_multi: boolean}>,
    useMultiUnit: false,
    currentUnit: null as any,
    unitTable: [] as UnitTableItem[],
    enableStockWarning: false,
    enableWarehouseWarning: false,
    warehouseWarningList: [] as WarehouseWarningItem[]
})

// 多计量单位转换
const handleUnitChange = (unitId: string | number) => {
    const unit = state.units.find(u => u.id === unitId)
    if (unit) {
        state.currentUnit = unit
        buildUnitTable(unit)
    }
}

// 构建多计量单位表格
const buildUnitTable = (unit: any) => {
    if (!unit) return
    
    // 清空表格
    state.unitTable = []
    
    // 解析计量单位名称和转换率
    const names = unit.name ? unit.name.split(',') : []
    const rates = unit.conversion ? unit.conversion.split(':') : []
    
    // 至少有一个基础单位
    if (names.length >= 1) {
        for (let i = 0; i < names.length; i++) {
            const rate = rates[i] ? parseFloat(rates[i]) : 1
            state.unitTable.push({
                name: names[i],
                unit_code: i === 0 ? '基本单位' : '副单位',
                rate: rate,
                retail_price: 0,
                wholesale_price: 0,
                vip_price: 0,
                discount1: 0,
                discount2: 0,
                purchase_price: 0
            })
        }
    }
}

// 处理多计量单位选择变更
const handleMultiUnitChange = async (val: boolean | string | number) => {
    // 将输入转换为布尔值
    const isChecked = Boolean(val)
    state.useMultiUnit = isChecked
    
    // 根据是否启用多计量单位，加载不同的单位数据
    if (isChecked) {
        await loadMultiUnitData()
    } else {
        await loadSingleUnitData()
    }
    
    // 清空当前选中的内容
    props.baTable.form.items.unit_id = null
    state.currentUnit = null
    state.unitTable = []
    
    // 自动选中第一个选项
    if (state.units.length > 0) {
        props.baTable.form.items.unit_id = state.units[0].id
        handleUnitChange(state.units[0].id)
    }
}

// 加载多计量单位数据
const loadMultiUnitData = async () => {
    try {
        const res = await getSelectData('/admin/yxerp.unit.conversion/', '', { select: true })
        if (res && Array.isArray(res.data.list)) {
            state.units = res.data.list
            // 如果没有选择单位且有单位数据，默认选择第一个
            if ((!props.baTable.form.items.unit_id || !state.currentUnit) && state.units.length > 0) {
                props.baTable.form.items.unit_id = state.units[0].id
                handleUnitChange(state.units[0].id)
            }
        }
    } catch (error) {
        console.error('加载多计量单位数据失败:', error)
    }
}

// 加载单计量单位数据
const loadSingleUnitData = async () => {
    try {
        const res = await getSelectData('/admin/yxerp.unit/', '', { select: true })
        if (res && Array.isArray(res.data.list)) {
            state.units = res.data.list
            // 如果没有选择单位且有单位数据，默认选择第一个
            if ((!props.baTable.form.items.unit_id || !state.currentUnit) && state.units.length > 0) {
                props.baTable.form.items.unit_id = state.units[0].id
                handleUnitChange(state.units[0].id)
            }
        }
    } catch (error) {
        console.error('加载单计量单位数据失败:', error)
    }
}

// 上传图片前的验证
const beforeImageUpload: UploadProps['beforeUpload'] = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
        ElMessage.error('上传图片只能是图片格式!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!')
        return false
    }
    return true
}



// 处理图集上传成功
const handleGallerySuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    if (response.code === 1) {
        if (!props.baTable.form.items.images) {
            props.baTable.form.items.images = []
        }
        props.baTable.form.items.images.push(response.data.url)
        
        // 更新显示的图片列表
        imagesList.value.push({
            name: uploadFile.name,
            url: response.data.url
        })
    } else {
        ElMessage.error(response.msg || '上传失败')
    }
}

// 处理图集删除
const handleGalleryRemove = (uploadFile: any) => {
    const index = imagesList.value.findIndex(item => item.url === uploadFile.url)
    if (index > -1) {
        imagesList.value.splice(index, 1)
        props.baTable.form.items.images.splice(index, 1)
    }
}

// 执行富文本编辑器命令
const execCommand = (command: string) => {
    document.execCommand(command, false)
    if (command === 'insertImage') {
        const url = prompt('请输入图片URL:')
        if (url) {
            document.execCommand('insertImage', false, url)
        }
    } else if (command === 'createLink') {
        const url = prompt('请输入链接URL:')
        if (url) {
            document.execCommand('createLink', false, url)
        }
    }
    
    // 更新表单内容
    updateDescription()
}

// 执行字体命令
const execFontCommand = (event: Event) => {
    const target = event.target as HTMLSelectElement
    if (target.value) {
        document.execCommand('fontName', false, target.value)
        target.value = ''
        updateDescription()
    }
}

// 执行字体大小命令
const execSizeCommand = (event: Event) => {
    const target = event.target as HTMLSelectElement
    if (target.value) {
        document.execCommand('fontSize', false, target.value)
        target.value = ''
        updateDescription()
    }
}

// 更新商品描述
const updateDescription = () => {
    if (editorRef.value) {
        props.baTable.form.items.description = editorRef.value.innerHTML
    }
}

// 构建仓库预警表格
const buildWarehouseWarningList = () => {
    state.warehouseWarningList = []
    
    state.warehouses.forEach(warehouse => {
        state.warehouseWarningList.push({
            warehouse_id: warehouse.id,
            warehouse_name: warehouse.name,
            min_stock: 0,
            max_stock: 0
        })
    })
}

// 加载分类数据
const loadCategoryData = async () => {
    try {
        const res = await new baTableApi('/admin/yxerp.category/').index()
        if (res.data && res.data.list) {
            state.category = res.data.list
        }
    } catch (error) {
        console.error('加载分类数据失败:', error)
    }
}

// 加载仓库数据
const loadWarehouseData = async () => {
    try {
        const res = await new baTableApi('/admin/yxerp.warehouse/').index()
        if (res.data && res.data.list) {
            state.warehouses = res.data.list
            // 构建仓库预警列表
            buildWarehouseWarningList()
        }
    } catch (error) {
        console.error('加载仓库数据失败:', error)
    }
}

// 初始化图片列表
const initImagesList = () => {
    imagesList.value = []
    if (props.baTable.form.items.images && Array.isArray(props.baTable.form.items.images)) {
        props.baTable.form.items.images.forEach((url: string, index: number) => {
            imagesList.value.push({
                name: `图片${index + 1}`,
                url: url
            })
        })
    }
}

// 初始化库存预警数据
const initStockWarning = () => {
    // 检查是否启用库存预警
    state.enableStockWarning = !!props.baTable.form.items.enable_stock_warning
    
    // 检查是否启用分仓预警
    state.enableWarehouseWarning = !!props.baTable.form.items.warehouse_warning_data
    
    // 填充分仓预警数据
    if (state.enableStockWarning && props.baTable.form.items.warehouse_warning_data) {
        try {
            const warningData = JSON.parse(props.baTable.form.items.warehouse_warning_data)
            if (Array.isArray(warningData)) {
                // 将数据合并到预警列表
                for (const item of warningData) {
                    const index = state.warehouseWarningList.findIndex(w => w.warehouse_id === item.warehouse_id)
                    if (index !== -1) {
                        state.warehouseWarningList[index].min_stock = item.min_stock || 0
                        state.warehouseWarningList[index].max_stock = item.max_stock || 0
                    }
                }
            }
        } catch (e) {
            console.error('解析仓库预警数据失败:', e)
        }
    }
}

// 初始化
onMounted(async () => {
    await loadCategoryData()
    await loadWarehouseData()
    
    // 根据是否使用多计量单位加载相应的单位数据
    if (props.baTable.form.items && props.baTable.form.items.multi_unit_data) {
        state.useMultiUnit = true
        await loadMultiUnitData()
    } else {
        await loadSingleUnitData()
    }
    props.baTable.form.items.retail_price = 0;
    props.baTable.form.items.wholesale_price = 0;
    props.baTable.form.items.vip_price = 0;
    props.baTable.form.items.discount1 = 0;
    props.baTable.form.items.discount2 = 0;
    props.baTable.form.items.purchase_price = 0;
    props.baTable.form.items.promotion_status = 0;
    props.baTable.form.items.order_status = 1;
    props.baTable.form.items.is_popular = 0;
    props.baTable.form.items.is_retail = 0;
    props.baTable.form.items.status = 1;
    props.baTable.form.items.min_stock = 0;
    props.baTable.form.items.max_stock = 0;
    props.baTable.form.items.shelf_life_days = 0;
    props.baTable.form.items.warning_days = 0;
    props.baTable.form.items.category_id = 33;
    props.baTable.form.items.enable_batch_management = false;
    props.baTable.form.items.enable_serial_management = false;
    props.baTable.form.items.enable_initial_setting = false;
    // 初始化表单默认值
    if (props.baTable.form.operate === 'Add') {
        const coderes = await getNextCode({
            code_type: 'product'
        })

        const barcoderes = await getcode({
            code_type: 'product_barcode'
        })
        
        // 设置默认值
        if (!props.baTable.form.items.code) props.baTable.form.items.code = coderes.data
        if (!props.baTable.form.items.barcode) props.baTable.form.items.barcode = barcoderes.data
        if (!props.baTable.form.items.status) props.baTable.form.items.status = 1
        if (!props.baTable.form.items.promotion_status) props.baTable.form.items.promotion_status = 0
        if (!props.baTable.form.items.order_status) props.baTable.form.items.order_status = 1
        if (!props.baTable.form.items.is_popular) props.baTable.form.items.is_popular = 0
        if (!props.baTable.form.items.is_retail) props.baTable.form.items.is_retail = 0
        if (!props.baTable.form.items.images) props.baTable.form.items.images = []
        if (!props.baTable.form.items.enable_batch_management) props.baTable.form.items.enable_batch_management = false
        if (!props.baTable.form.items.enable_serial_management) props.baTable.form.items.enable_serial_management = false
        if (!props.baTable.form.items.enable_initial_setting) props.baTable.form.items.enable_initial_setting = false
        
        // 自动选中第一个计量单位选项
        if (!props.baTable.form.items.unit_id && state.units.length > 0) {
            props.baTable.form.items.unit_id = state.units[0].id
            handleUnitChange(state.units[0].id)
        }
            if (!props.baTable.form.items.default_warehouse_id && state.warehouses.length > 0) {
                props.baTable.form.items.default_warehouse_id = state.warehouses[0].id
                //handleUnitChange(state.warehouses[0].id)
            }
        if (!props.baTable.form.items.category && state.category.length > 0) {
            props.baTable.form.items.category = state.category[0].id
        }
        if (!props.baTable.form.items.category_id && state.category.length > 0) {
            props.baTable.form.items.category_id = state.category[0].id
        }

       
    } else if (props.baTable.form.operate === 'Edit') {
        // 初始化图片列表
        initImagesList()
        
        // 如果有单位，初始化多计量单位表格
        if (props.baTable.form.items.unit_id) {
            const unit = state.units.find(u => u.id === props.baTable.form.items.unit_id)
            if (unit) {
                state.currentUnit = unit
                // 检查是否使用多计量单位
                state.useMultiUnit = !!props.baTable.form.items.multi_unit_data
                
                if (state.useMultiUnit) {
                    buildUnitTable(unit)
                    
                    // 如果已经有多计量单位数据，填充到表格中
                    if (props.baTable.form.items.multi_unit_data && typeof props.baTable.form.items.multi_unit_data === 'string') {
                        try {
                            const multiUnitData = JSON.parse(props.baTable.form.items.multi_unit_data)
                            if (Array.isArray(multiUnitData) && multiUnitData.length > 0) {
                                state.unitTable.forEach((item, index) => {
                                    if (index < multiUnitData.length) {
                                        Object.assign(item, multiUnitData[index])
                                    }
                                })
                            }
                        } catch (e) {
                            console.error('解析多计量单位数据失败:', e)
                        }
                    }
                }
            }
        } else if (state.units.length > 0) {
            // 如果编辑模式下没有选择单位，自动选择第一个
            props.baTable.form.items.unit_id = state.units[0].id
            handleUnitChange(state.units[0].id)
        }
        
        // 初始化库存预警数据
        initStockWarning()
        
        // 如果是编辑模式且已有ID，则加载SKU列表
        if (props.baTable.form.items.id) {
            loadSkuList()
        }
    }
})

// 监听单位变更，自动重置多计量单位表格
watch(() => props.baTable.form.items.unit_id, (newVal) => {
    if (newVal) {
        handleUnitChange(newVal)
    } else {
        state.unitTable = []
    }
})

// 打开SKU表单
const openSkuForm = (action: string, row?: any) => {
    skuAction.value = action
    skuFormTitle.value = action === 'Add' ? t('Add SKU') : t('Edit SKU')
    
    // 重置表单
    skuForm.value = {
        product_id: props.baTable.form.items.id,
        sku_code: '',
        price: 0,
        cost: 0,
        stock: 0,
        attributes: {}
    }
    
    attributesList.value = []
    
    // 编辑模式，填充数据
    if (action === 'Edit' && row) {
        skuForm.value = { ...row }
        
        // 转换属性列表
        if (row.attributes && typeof row.attributes === 'object') {
            attributesList.value = Object.entries(row.attributes).map(([key, value]) => ({
                key,
                value: value as string
            }))
        }
    }
    
    skuDialogVisible.value = true
}

// 删除SKU
const delSku = async (row: any) => {
    ElMessageBox.confirm(t('确定要删除此SKU吗？'), t('提示'), {
        confirmButtonText: t('确定'),
        cancelButtonText: t('取消'),
        type: 'warning',
    }).then(async () => {
        try {
            await api.del([row.id])
            ElMessage.success(t('删除成功'))
            loadSkuList()
        } catch (error) {
            console.error('删除SKU失败:', error)
        }
    }).catch(() => {})
}

// 添加属性
const addAttribute = () => {
    attributesList.value.push({ key: '', value: '' })
}

// 移除属性
const removeAttribute = (index: number) => {
    attributesList.value.splice(index, 1)
}

// 提交SKU表单
const submitSkuForm = async () => {
    // 构建attributes对象
    const attributes: Record<string, string> = {}
    attributesList.value.forEach(item => {
        if (item.key && item.value) {
            attributes[item.key] = item.value
        }
    })
    
    skuForm.value.attributes = attributes
    
    try {
        const action = skuAction.value === 'Add' ? 'add' : 'edit'
        await api.postData(action, skuForm.value)
        
        ElMessage.success(t('操作成功'))
        skuDialogVisible.value = false
        loadSkuList()
    } catch (error) {
        console.error('提交SKU表单失败:', error)
    }
}

// 加载SKU列表
const loadSkuList = async () => {
    if (!props.baTable.form.items.id) return
    
    try {
        const res = await api.index({ product_id: props.baTable.form.items.id })
        if (res.data && res.data.list) {
            skuList.value = res.data.list.map((item: any) => {
                // 处理attributes字段，确保是对象
                if (item.attributes && typeof item.attributes === 'string') {
                    try {
                        item.attributes = JSON.parse(item.attributes)
                    } catch (e) {
                        item.attributes = {}
                    }
                }
                return item
            })
        }
    } catch (error) {
        console.error('加载SKU列表失败:', error)
    }
}

// 在表单提交前处理数据
const prepareSubmitData = () => {
    // 处理多计量单位数据
    if (state.useMultiUnit && state.unitTable.length > 0) {
        props.baTable.form.items.multi_unit_data = JSON.stringify(state.unitTable)
    } else {
        props.baTable.form.items.multi_unit_data = null
    }
    
    // 处理库存预警数据
    props.baTable.form.items.enable_stock_warning = state.enableStockWarning

    // 处理分仓预警数据
    if (state.enableStockWarning && state.enableWarehouseWarning && state.warehouseWarningList.length > 0) {
        props.baTable.form.items.warehouse_warning_data = JSON.stringify(state.warehouseWarningList)
    } else {
        props.baTable.form.items.warehouse_warning_data = null
    }
    
    return props.baTable.form.items
}

// 导出表单引用和提交前处理函数，供父组件使用
defineExpose({
    formRef,
    prepareSubmitData
})
</script>

<style lang="scss" scoped>
.ba-form-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.attribute-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.el-tag {
    margin-right: 5px;
    margin-bottom: 5px;
}

.w100 {
    width: 100%;
}

.multi-unit-table {
    margin-top: 20px;
    margin-left: 120px;
}

.ml-30 {
    margin-left: 30px;
}

.avatar-uploader {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 178px;
    height: 178px;
    
    &:hover {
        border-color: var(--el-color-primary);
    }
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
}

.editor-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
}

.editor-toolbar {
    padding: 10px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #dcdfe6;
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
}

.editor-btn {
    padding: 5px 10px;
    background-color: white;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    
    &:hover {
        background-color: #ecf5ff;
        color: #409eff;
    }
}

.editor-select {
    padding: 5px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
}

.editor-content {
    min-height: 300px;
    padding: 10px;
    outline: none;
    overflow-y: auto;
}
</style>
